import os
from pdf_parser import PDFParser
from translator.translator_factory import TranslatorFactory
import my_app_config
from document.write import Writer

class PDFTranslator:
    def __init__(self):
        self.parser = PDFParser()
        self.translator = TranslatorFactory().get_translator(my_app_config.my_app_config.model)

    def translate(self, src: str, target=None, target_language='中文'):
        if target == None:
            target = self.getTranslatedPDF(src)

        document = self.parser.parse(src)
        for p in document.pages:
            for c in p.contents:
                c.translation = self.translator.translate(c.original, target_language)
        Writer().save_translated_book(document, target)
        return os.path.basename(target)

    def getTranslatedPDF(self, src: str) -> str:
        """
        在源文件名称后面增加“_trans”的后缀，表示翻译后的文件
        :param src: 源文件
        :return: 修改后的文件名
        """
        filename = os.path.basename(src)  # 获取文件名，不包括路径
        filename_without_ext, ext = os.path.splitext(filename)  # 分割文件名和扩展名
        new_filename = filename_without_ext + "_trans" + ext  # 修改扩展名
        new_path = os.path.join(os.path.dirname(src), new_filename)  # 重新组合路径和新的文件名
        return new_path

if __name__ == '__main__':
    PDFTranslator().translate('d:/ee.pdf')